package com.dm.service.user_login;


import com.dm.common.*;
import com.dm.service.mail.MailService;
import com.dm.service.sms.SmsService;
import com.dm.vo.DmUserVO;
import com.dm.vo.TokenVO;
import com.dm.client.dm_base.RestDmImageClient;
import com.dm.client.dm_user.RestDmUserClient;
import com.dm.pojo.dm_base.DmImage;
import com.dm.pojo.dm_user.DmUser;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
@Service
public class LoginDmUserImpl implements LoginDmUser {

    @Resource
    private RestDmUserClient restDmUserClient;
    @Resource
    private RestDmImageClient restDmImageClient;
    @Resource
    private SmsService smsService;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private MailService mailService;
    @Resource
    private KafKaUtil kafKaUtil;
    /**
     * 根据号码和密码查询用户
     * @param phone
     * @param password
     * @return
     * @throws Exception
     */
    @Override
    public DmUserVO queryUser_PhoneAndPassword(String phone, String password) throws Exception {
        DmUserVO dmUserVO=new DmUserVO();
        Map<String,Object> userMap=new HashMap<String,Object>();
        userMap.put("phone",phone);
        userMap.put("password", password==null?password=null:MD5.getMd5(password,32));
        //获取用户
        List<DmUser> listUser = restDmUserClient.getDmUserListByMap(userMap);

        if(EmptyUtils.isEmpty(listUser)){
            return null;
        }else {
            //更新用户头像数据
            Map<String,Object> imgParam = new HashMap<>();
            imgParam.put("targetId",listUser.get(0).getId());
            imgParam.put("category", Constants.Image.ImageCategory.user);
            DmImage dmImage=restDmImageClient.getDmImageListByMap(imgParam).get(0);
            dmUserVO.setImageId(dmImage.getId());
            dmUserVO.setImgUrl(dmImage.getImgUrl());
            BeanUtils.copyProperties(listUser.get(0),dmUserVO);
            dmUserVO.setUserId(listUser.get(0).getId());
            return dmUserVO;
        }
    }


    /**
     * 合并用户和token
     * @param dmUserVO
     * @param tokenKey
     * @return
     * @throws Exception
     */
    @Override
    public List<Object> mergeByUser_Token(String tokenKey, DmUserVO dmUserVO) throws Exception {
        TokenVO tokenVO=new TokenVO();
        tokenVO.setToken(tokenKey);
        //有效时间
        tokenVO.setExpTime(Constants.Redis_Expire.SESSION_TIMEOUT);

        String[] key=tokenKey.split("-");
        String gentime=key[3];
        Date date=new SimpleDateFormat("yyyyMMdd").parse(gentime);
        //生成时间
        tokenVO.setGenTime(date.getTime());
        List<Object> listObject=new ArrayList<>();
        listObject.add(dmUserVO);
        listObject.add(tokenVO);

        return listObject;
    }


    /**
     * 创建微信token
     * @param userInfoJsonstr
     * @return
     * @throws Exception
     */
  /*  @Override
    public String createWxUserToken(String userInfoJsonstr) throws Exception {
        JSONObject userInfoJson=JSONObject.parseObject(userInfoJsonstr);
        String openId=userInfoJson.getString("openid");
        Map<String,Object> param=new HashMap<String,Object>();
        List<QgUser> qgUserList=qgUserService.getQgUserListByMap(param);
        QgUser qgUser=null;
        //如果不在库中，说明用户首次进行微信登录
        if(EmptyUtils.isEmpty(qgUserList)){
            qgUser=new QgUser();
            qgUser.setId(IdWorker.getId());
            qgUser.setCreatedTime(new Date());
            qgUser.setRealName(userInfoJson.getString("nickname"));
            qgUser.setUpdatedTime(new Date());
            qgUser.setWxUserId(openId);
            qgUserService.qdtxAddQgUser(qgUser);
        }else{
            qgUser=qgUserList.get(0);
        }
        //为用户执行自动登录的操作
        String token= Constants.tokenPrefix+ TokenUtils.createToken(qgUser.getId(),qgUser.getWxUserId());
        redisUtil.setStr(token, JSONObject.toJSONString(qgUser), new Long(Constants.TOKEN_TIMEOUT));
        redisUtil.setStr(qgUser.getId(), token,new Long(Constants.TOKEN_TIMEOUT));
        return token;
    }*/
    /**
     * 验证邮箱格式
     *
     * @param email
     * @return
     */
    @Override
    public boolean validEmail(String email) {
        String regex = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-z-A-Z0-9]+)*\\.[a-z-A-Z]+\\s*$";
        return Pattern.compile(regex).matcher(email).find();

    }


    /**
     * 验证手机号格式
     *
     * @param phon
     * @return
     */
    @Override
    public boolean validPhon(String phon) {
        String regex = "^1[3578]{1}\\d{9}$";
        return Pattern.compile(regex).matcher(phon).find();

    }

    /**
     * 发送手机验证码等
     *
     * @param phone
     * @throws Exception
     */
    @Override
    public String sendPhon(String prifix,String phone) throws Exception {
        //生成验证码
        Integer rand = MD5.getRandomCode();
        //发送验证码
        smsService.sendSms(phone, "1", new String[]{rand.toString(), "1"});
        //并存入redis

        redisUtils.set(prifix+phone, 60, rand.toString());
        return rand.toString();
    }

    /**
     * 发送邮箱验证码等
     *
     * @param phone
     * @throws Exception
     */
    @Override
    public String sendMail(String prifix,String phone) throws Exception {

        //生成激活码
        Integer activationCode = MD5.getRandomCode();
        //发送邮件
        mailService.sendActivationMail(phone, activationCode.toString());

        //激活码存入redis
        redisUtils.set(prifix+phone, 300, activationCode.toString());
        return activationCode.toString();
    }
    /**
     * 添加注册用户
     * @param phone
     * @param password
     */
    @Override
    public void addRegisterUser(String phone,String password)throws Exception{
        DmUser dmUser=new DmUser();
        dmUser.setPhone(phone);
        dmUser.setPassword(MD5.getMd5(password,32));
        dmUser.setCreatedTime(new Date());
        dmUser.setUpdatedTime(new Date());
        kafKaUtil.sendInfoMessage("注册成功");
        restDmUserClient.qdtxAddDmUser(dmUser);
    }
}
